package service

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"os"
	"path"
	"strings"
	"time"
)

func FileHandle(r *gin.Engine) {
	file := r.Group("/:module/file")
	{
		file.GET("/rename", fileRename)
		file.GET("/list", fileList)
		file.POST("/save", fileSave)
	}
}

func fileRename(c *gin.Context) {
	sql.HttpHandle(sql.UPDATE, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		id := c.Query("id")
		createTime := c.Query("createTime")
		var bean model.FileInfo
		db = db.Model(&bean).Where("id = ?", id)
		if createTime != "" {
			db.Update("create_time", createTime)
		}
		return db, bean
	})
}

func fileList(c *gin.Context) {
	sql.HttpHandle("获取", c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		var list []model.FileInfo
		module := c.Param("module") //模块_属性
		attribute := ""             //属性
		if index := strings.Index(module, "_"); index != -1 {
			attribute = module[index+1:] //
			module = module[:index]
		}
		identification := c.Query("identification")
		if identification != "" {
			db = db.Where("identification = ?", identification)
		}
		if attribute != "" {
			db = db.Where("type = ?", attribute)
		}
		db.Find(&list)
		return db, list
	})
}

func fileSave(c *gin.Context) {
	sql.HttpHandle("保存", c, func(db *gorm.DB) (*gorm.DB, interface{}) {

		module := c.Param("module") //模块_属性
		attribute := ""             //属性
		if index := strings.Index(module, "_"); index != -1 {
			attribute = module[index+1:] //
			module = module[:index]
		}
		//文件夹
		folder := "./upload" + "/" + module
		//模块下文件夹名称
		childFolder := c.PostForm("folder")
		if childFolder != "" {
			folder = folder + "/" + childFolder
		}
		//创建文件
		if err := os.MkdirAll(folder, 0666); err != nil {
			db.Error = err
			return db, nil
		}

		form, err := c.MultipartForm()
		if err != nil {
			db.Error = err
			return db, nil
		}
		files := form.File["files[]"]
		identification := c.PostForm("identification")
		if identification == "" || files == nil {
			db.Error = errors.New(sql.ErrorParams)
			return db, nil
		}

		var list []model.FileInfo
		for _, file := range files {
			suffix := path.Ext(file.Filename) //文件后缀
			var fileName string
			if suffix == ".jpg" || suffix == ".png" {
				fileName = childFolder + "_" + file.Filename
			} else {
				fileName = file.Filename
			}
			filePath := folder + "/" + fileName
			err := c.SaveUploadedFile(file, filePath)
			if err != nil {
				db.Error = err
				return db, nil
			}
			var bean model.FileInfo
			bean.CreateTime = time.Now().Format("2006-01-02 15:04:05")
			bean.Identification = identification
			bean.Module = module
			bean.Type = attribute
			bean.Name = fileName
			bean.Path = filePath[1:]
			bean.Suffix = suffix
			bean.Size = file.Size
			db.Create(&bean)
			list = append(list, bean)
		}
		return db, list
	})
}
